package quartz.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.quartz.*;
import org.springframework.stereotype.Service;
import quartz.demo.entity.QuartzBean;
import quartz.demo.mapper.QuartzMapper;
import quartz.demo.service.QuartzService;
import quartz.demo.util.QuartzUtil;
import javax.annotation.Resource;
import java.util.Date;

@Service
public class QuartzServiceImpl extends ServiceImpl<QuartzMapper, QuartzBean> implements QuartzService {

    @Resource
    private Scheduler scheduler;
    @Resource
    private QuartzUtil quartzUtil;

    // 立即执行一次
    @Override
    public void execute(QuartzBean quartzBean) throws Exception {
        String implClass = quartzBean.getImplClass().trim();
        String name = quartzBean.getCode();
        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity(name, quartzBean.getQuartzGroup())
                .startAt(new Date())
                .build();
        JobDetail jobDetail = JobBuilder.newJob(QuartzUtil.getClass(implClass).getClass()).withIdentity(name).usingJobData("parameter", "param").build();
        scheduler.scheduleJob(jobDetail, trigger);
        // 启动scheduler
        scheduler.start();
    }

    // 执行定时任务
    @Override
    public void beginExecute() {
        QuartzBean quartzBean = this.getById(1);
        quartzUtil.schedulerDelete(quartzBean.getCode());
        quartzUtil.schedulerAdd(quartzBean.getCode(), quartzBean.getImplClass().trim(), quartzBean.getCorn().trim(), "param");
        quartzBean.setStatus(1);
        this.updateById(quartzBean);
    }

    // 暂停定时任务
    @Override
    public void pause(QuartzBean quartzBean) {
        quartzUtil.schedulerDelete(quartzBean.getCode());
        quartzBean.setStatus(0);
        this.updateById(quartzBean);
    }

    //  修改定时任务
    @Override
    public void updateJob(QuartzBean quartzBean) throws SchedulerException {
        if (1 == quartzBean.getStatus()) {
            // 修改状态为启动
            quartzUtil.schedulerDelete(quartzBean.getName());
            quartzUtil.schedulerAdd(quartzBean.getCode(), quartzBean.getImplClass().trim(), quartzBean.getCorn().trim(), "param");
        } else {
            // 修改状态为停止
            scheduler.pauseJob(JobKey.jobKey(quartzBean.getCode()));
        }
        this.updateById(quartzBean);
    }

    // 删除定时任务
    @Override
    public void delete(int id) {
        QuartzBean quartzBean = this.getById(id);
        quartzUtil.schedulerDelete(quartzBean.getCode());
    }

    // 添加定时任务
    @Override
    public void add(QuartzBean quartzBean) {
        quartzBean.setIsDel(0);
        boolean success = this.save(quartzBean);
        if (success) {
            if (1 == quartzBean.getStatus()) {
                quartzUtil.schedulerAdd(quartzBean.getCode(), quartzBean.getImplClass().trim(), quartzBean.getCorn().trim(), "param");
            }
        }

    }
}
